package com.bright.service.serviceimpl;

import com.bright.dao.TagDao;
import com.bright.pojo.Blog;
import com.bright.pojo.Tag;
import com.bright.pojo.Type;
import com.bright.service.TagService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagDao tagDao;

    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagDao.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(long id) {
        return tagDao.getOne(id);
    }

    @Transactional
    @Override
    public Page<Tag> getTags(Pageable pageable) {
        return tagDao.findAll(pageable);
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagDao.findAllById(convertTolist(ids));
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Pageable pageable = PageRequest.of(0,size,Sort.by(Sort.Direction.DESC,"blogs.size"));
        return tagDao.findTop(pageable);
    }

    @Override
    public List<Blog> listTagBlog(long id) {
        List<Blog> blogs = new ArrayList<>();
        Tag tag = tagDao.getOne(id);
        blogs = tag.getBlogs();
        return blogs;
    }

    private List<Long> convertTolist(String ids){
        List<Long> idlist = new ArrayList<>();
        if (!StringUtil.isNullOrEmpty(ids)){
            String [] idarray = ids.split(",");
            for (int i = 0; i < idarray.length; i++) {
                idlist.add(new Long(idarray[i]));
            }
        }
        return idlist;
    }

    @Transactional
    @Override
    public Tag update(long id, Tag tag) {
        return null;
    }

    @Transactional
    @Override
    public void delete(long id) {
        tagDao.deleteById(id);
    }

    @Transactional
    @Override
    public Tag getTagByName(String tagname) {
        return tagDao.findByName(tagname);
    }
}
